package com.qire.manhua.dal.service;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.constant.AdvertManage;
import com.qire.common.constant.CustomEvent;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.NoticeEventBus;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.snackbar.Prompt;
import com.qire.manhua.dal.ITaskDataDAL;
import com.qire.manhua.dal.IUserDataDAL;
import com.qire.common.model.enumeration.RewardType;
import com.qire.manhua.model.viewModel.impl.TaskCenterViewModel;
import com.qire.manhua.model.viewModel.impl.TaskCenterViewModel.TaskItemViewModel;
import com.qire.manhua.model.vo.OkResponseVO;
import com.qire.manhua.model.vo.SignInResponseVO;
import com.qire.manhua.model.vo.SignInInfoVO;
import com.qire.manhua.model.vo.TaskListDataVO;
import com.qire.manhua.model.vo.TaskListDataVO.TaskDataItemVO;
import com.qire.manhua.model.vo.UserDetailVO;
import com.qire.other.thirdPlatform.WeChatPlatform;

import androidx.fragment.app.FragmentActivity;

public class TaskCenterService extends DataService {

    private final ITaskDataDAL taskDataDAL = WarehouseFactory.create(this, ITaskDataDAL.class);
    private final IUserDataDAL userDataDAL = WarehouseFactory.create(this, IUserDataDAL.class);

    private final TaskCenterViewModel viewModel;

    public TaskCenterService(TaskCenterViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * 加载任务列表数据
     */
    public void loadTaskListData() {
        taskDataDAL.fetchTaskList();
    }
    @StrategyAnnotation(event = Url.TaskList)
    public void fetchTaskListCallback(TaskListDataVO taskDataVO, boolean isCache) {
        viewModel.clearDailyTaskList();
        for(TaskDataItemVO itemVO : taskDataVO.daily_task) {
            viewModel.addDailyTaskItem(itemVO.toTaskEntity());
        }

        viewModel.clearNewcomerTaskList();
        for(TaskDataItemVO itemVO : taskDataVO.aims_task) {
            viewModel.addNewcomerTaskItem(itemVO.toTaskEntity());
        }

        viewModel.refreshAdapter();
    }

    /**
     * 加载签到信息
     */
    public void loadSignInInfo() {
        taskDataDAL.fetchSignInInfo();
    }
    @StrategyAnnotation(event = Url.sign_info)
    public void fetchSignInInfoApiCallbackRefresh(SignInInfoVO signInResponseVO, boolean isCache) {
        if(signInResponseVO.is_sign == 0) {
            signIn();
            return;
        }
        String[] nodeTexts = new String[7];
        for(int index=0; index<7; index++) {
            nodeTexts[index] = String.valueOf(signInResponseVO.init_gold + (index * signInResponseVO.accumulate));
        }

        viewModel.changeSignInPanelData(signInResponseVO.tips, signInResponseVO.is_new == 1, nodeTexts, signInResponseVO.sign_count);
    }

    /**
     * 签到
     */
    private void signIn() {
        taskDataDAL.signIn();
    }
    @StrategyAnnotation(event = Url.SignIn)
    public void signInCallback(SignInResponseVO signInResponseVO, boolean isCache) {
        final String signInDoubleKey = signInResponseVO.sign_dbl;
        viewModel.showReceiveTaskRewardsDialog("签到成功", String.format("+%s金豆", signInResponseVO.today_bean), RewardType.Bean, true, view -> {
            viewModel.showLoadDialog();
            AdvertManage.AdvertSpace.TaskDoubleReceive.build()
                    .setSize(EquipmentInfoUtil.getScreenWidth(), 0)
//                    .setClosedListener(() -> ToastHelper.showToast("您取消了视频播放，放弃了领取双倍奖励！"))
                    .setClosedListener(() -> signInRewardDouble(signInDoubleKey))
                    .setErrorListener(() -> {
                        viewModel.dismissLoadDialog();
                        ToastHelper.showToast("运行错误，请联系客服或稍后再试！");
                    })
                    .setStartListener(viewModel::dismissLoadDialog)
                    .playVideo((FragmentActivity) ActivityManageHandler.HANDLER.currentActivity());
        });
        loadSignInInfo();
        refreshUserDetailData();
        NoticeEventBus.NOTICE.sendEvent(CustomEvent.SIGN_IN);
    }
    /**
     * 签到双倍奖励领取
     */
    public void signInRewardDouble(String signInDoubleKey) {
        taskDataDAL.signInRewardDouble(signInDoubleKey);
    }
    @StrategyAnnotation(event = Url.SignInRewardDouble)
    public void signInRewardDoubleCallback(SignInResponseVO signInResponseVO, boolean isCache) {
        viewModel.showReceiveTaskRewardsDialog("签到成功", String.format("+%s金豆", signInResponseVO.today_bean),
                RewardType.Bean, false, null);
        refreshUserDetailData();
    }


    /**
     * 绑定微信
     */
    public void bindWeChat() {
        viewModel.showLoadDialog("请稍等");
        WeChatPlatform.WeChat.authorize((msg, info) -> {
            viewModel.dismissLoadDialog();
            if(ObjectUtil.nonNull(info)) {
                userDataDAL.weChatBind(info.unionid, info.openid, info.nickname);
            }
        });
    }
    @StrategyAnnotation(event = Url.WeChatBind)
    public void weChatBindCallback(OkResponseVO dataVO, boolean isCache) {
        ToastHelper.showSnackBar(dataVO.ok, Prompt.SUCCESS);
        viewModel.showBindWeChatResultDialog();
        refreshUserDetailData();
    }

    /**
     * 同步刷新用户资料，更新余额
     */
    public void refreshUserDetailData() {
        // todo 可以的话，有那个这个类替换所有对于操作完后需要刷新同步用户数据的操作
        userDataDAL.refreshUserDetailData();
    }
    @StrategyAnnotation(event = Url.myIndex)
    public void refreshUserDetailDataCallback(UserDetailVO dataVO, boolean isCache) {
        if(isCache || ObjectUtil.isNull(dataVO)) {
            return;
        }
        dataVO.updateUserEntity();
    }


    private TaskItemViewModel itemViewModel;
    /**
     * 通过任务ID领取任务奖励
     * @param itemViewModel 任务项目
     */
    public void receiveRewardBy(final TaskItemViewModel itemViewModel) {
        this.itemViewModel = itemViewModel;
        viewModel.showLoadDialog("正在领取");
        taskDataDAL.receiveAward(itemViewModel.taskID());
    }
    @StrategyAnnotation(event = Url.v5_receiveAward)
    public void receiveAwardApiCallbackRefresh(OkResponseVO vo, boolean isCache) {
        viewModel.dismissLoadDialog();

        itemViewModel.showReward();

        refreshUserDetailData();
        // 刷新任务列表
        loadTaskListData();
    }

}
